package com.bort.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bort.system.common.DataContainer;
import com.bort.system.mapper.CartMapper;
import com.bort.system.mapper.GoodsMapper;
import com.bort.system.mapper.OrderMapper;
import com.bort.system.model.Goods;
import com.bort.system.model.TOrder;
import com.bort.system.model.User;
import com.bort.system.model.vo.GoodsVo;
import com.bort.system.service.GoodsService;
import com.bort.system.utils.FileUtils;
import com.bort.system.utils.Result;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    @Resource
    GoodsMapper goodsMapper;

    @Resource
    FileUtils fileUtils;

    @Resource
    OrderMapper orderMapper;

    @Resource
    CartMapper cartMapper;

    @Override
    public Result<Page<GoodsVo>> getGoodsList(Page<GoodsVo> pager, Map<String, Object> map) {
        List<GoodsVo> list = goodsMapper.getGoodsByPager(pager,map);
        pager.setRecords(list);
        return Result.success(pager);
    }

    @Override
    public boolean addGoods(Goods goods) {
        Subject subject = SecurityUtils.getSubject();
        User principal = (User) subject.getPrincipal();
        goods.setCreateTime(new Date());
        goods.setCreateUserId(principal.getId());
        String goodsCode = "RM"+DateFormatUtils.format(new Date(), "yyMMddHHmmss");
        goods.setGoodsCode(goodsCode);
        goods.setSold(0);
        return save(goods);
    }


    @Override
    public boolean updateGoods(Goods goods) {
        return updateById(goods);
    }

    @Override
    public boolean deleteGoods(Integer id) {
        int del = goodsMapper.deleteById(id);
        return true;
    }

    @Override
    public Result upload(MultipartFile file) {
        return fileUtils.upload(file,"goods");
    }

    @Override
    public List<Goods> loadGoodsByCategoryId(Integer categoryId) {
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.eq("CATEGORY_ID",categoryId);
        wrapper.eq("STATUS",1);
        List<Goods> list = goodsMapper.selectList(wrapper);
        return list;
    }

}
